
pipeline {
    agent {
        node {
            label "label-master" // 指定运行节点的标签或名称
        }
    }

    options {
        timestamps()                    // 在日志中打印时间
        timeout(time:1, unit:'HOURS')   // 流水线超时设置为1H
        retry(2)                        // 失败重试2次
        skipDefaultCheckout() // 删除隐式的checkout scm 语句
        disableConcurrentBuilds() // 禁止并行
    }

    triggers {
        cron('0 5 * * 1-5')                         // 每周一到周五的5点触发
        // scm('*/5 * * * *')                       // SCM触发器，它将在每5分钟检测源代码管理系统（例如Git）的变化。如果有新的提交，则会触发Pipeline
        // upstream('My-Other-Job', 'SUCCESS')      // 外部触发器，它将在另一个名为My-Other-Job的Jenkins Job成功完成后触发Pipeline
    }

    environment  {
        EnvType = 'dev20'
        ProjectNames = 'trunklpg;SaaSAPPlpg;DccAdmin;NewWXShoplpg;09API_WebAPI;09API_WebAPI_LPG'
    }

    stages {

        stage("InitParamters") {
            steps {
                script {
                    json_file = "C:\\Jenkins\\resources\\input.lanyang.json"
                    Boolean isExists = fileExists json_file
                    if (!isExists) {
                        println "The Input_Json File does not exists."
                        error "This pipeline stops here!"
                    }
                    prop = readJSON file : json_file
                    
                    zipPath = prop.projects.zipPath ? prop.projects.zipPath : ""
                    println "zipPath: " + zipPath
                    excludeFolderPathBackup = prop.projects.excludeFolderPathBackup ? prop.projects.excludeFolderPathBackup : ""
                    println "excludeFolderPathBackup: " + excludeFolderPathBackup
                    excludeFilePathBackup = prop.projects.excludeFilePathBackup ? prop.projects.excludeFilePathBackup : ""
                    println "excludeFilePathBackup: " + excludeFilePathBackup                    
                }
            }
        }

        stage('Backup') { 
            steps {
                timeout(time:30, unit:'MINUTES') {
                    script {
                        for (project_name in ProjectNames.tokenize(';')) {
                            index = 0
                            for (site in prop.envs[EnvType][project_name]) {
                                siteName = site.siteName ? site.siteName : ""
                                webPath = site.webPath ? site.webPath : ""
                                appPoolName = site.appPoolName ? site.appPoolName : ""
                                healthUrl = site.healthUrl ? site.healthUrl : ""

                                bat """
                                    set projectName=${project_name}
                                    set webPath=${webPath}
                                    set zip="${zipPath}"
                                    set today=%date:~0,4%%date:~5,2%%date:~8,2%

                                    echo "[Debug:info] projectName=%projectName%"
                                    echo "[Debug:info] webPath=%webPath%"

                                    IF "%webPath%" == "" (
                                        echo "[Error:info] not exists web path: %webPath%"
                                        GOTO ERROR
                                    )

                                    cd /d %webPath%
                                    cd ..\\
                                    set fileName=%projectName%_%today%_${env.BUILD_NUMBER}.7z
                                    set zipFilePath=.\\backupPackages\\%fileName%

                                    echo "[Debug:info] start delete backup packages that more then 3 days"
                                    forfiles /p ".\\backupPackages" /s /m *.* /d -3 /c "cmd /c del @path"
                                    
                                    echo "[Debug:info] start zip %projectName% site to backup"
                                    %zip% a %zipFilePath% %webPath% -xr@"${excludeFolderPathBackup}" -x@"${excludeFilePathBackup}"
                                    IF %ERRORLEVEL% NEQ 0 GOTO ERROR

                                    :OK
                                    ECHO command success
                                    EXIT 0

                                    :ERROR
                                    ECHO command failed
                                    EXIT 1
                                """
                            }
                        }
                    }
                }
            }
        }
    }

    post {
        success {
            wrap([$class: 'BuildUser']) {
                echo '恭喜您，构建成功！！！'
                mail subject: "CI报告: ${env.JOB_NAME} [${env.BUILD_NUMBER}] 执行成功",
                body: """
                    <style>
                    ul li { padding: 8px 0; }
                    </style>
                    <div id="content">
                        <div id="sum2">
                            <h2><font color=#00CD00>Jenkins 运行成功</font></h2>
                            <ul>
                                <li>Jenkins Job Name : <a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a></li>
                                <li>Jenkins Job URL : <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                                <li>执行日志：<a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                                <li>执行环境: ${env.EnvType}</li>
                                <li>执行项目: <font color=#00CD00>${env.ProjectNames}</font></li>
                                <li>执行人：${BUILD_USER}</li>
                            </ul>
                        </div>
                    </div>
                    """,
                charset: 'utf-8',
                from: '2167162@qq.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}, lufei@lanyang.com"
            }
        }
        failure {
            wrap([$class: 'BuildUser']) {
                echo '抱歉，构建失败！！！'
                mail subject: "CI报告: ${env.JOB_NAME} [${env.BUILD_NUMBER}] 执行失败",
                body: """
                    <style>
                    ul li { padding: 8px 0; }
                    </style>
                    <div id="content">
                        <div id="sum2">
                            <h2><font color=#EE0000>Jenkins 运行失败</font></h2>
                            <ul>
                                <li>Jenkins Job Name : <a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a></li>
                                <li>Jenkins Job URL : <a href='${env.BUILD_URL}'>${env.BUILD_URL}</a></li>
                                <li>执行日志：<a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
                                <li>执行环境: ${env.EnvType}</li>
                                <li>执行项目: <font color=#EE0000>${env.ProjectNames}</font></li>
                                <li>执行人：${BUILD_USER}</li>
                            </ul>
                        </div>
                    </div>
                """,
                charset: 'utf-8',
                from: '2167162@qq.com',
                mimeType: 'text/html',
                to: "${env.BUILD_USER_EMAIL}, lufei@lanyang.com"
            }
        }
    }
}
